<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="680px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="24">
          <el-form-item label-width="125px" label="完工日期" prop="dateRange">
            <el-date-picker
              clearable
              size="small"
              v-model="dateRange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="125px" label="制造单号" prop="mofZzdh">
            <el-input
              v-model="queryParams.mofZzdh"
              placeholder="请输入制造单号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="125px" label="销售单号" prop="mofSodh">
            <el-input
              v-model="queryParams.mofSodh"
              placeholder="请输入销售单号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="125px" label="机台编号" prop="mofJtbh">
            <el-input
              v-model="queryParams.mofJtbh"
              placeholder="请输入机台编号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="125px" label="模具编号" prop="mofMjbh">
            <el-input
              v-model="queryParams.mofMjbh"
              placeholder="请输入模具编号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="125px" prop="mofWldm">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码，品名规格，客户编码查询"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input
              v-model="queryParams.mofWldm"
              clearable
              size="small"
              style="width: 400px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          v-hasPermi="['produce:mxSend:query']"
          size="mini"
          @click="handleSearch"
          >查询</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-position"
          size="mini"
          :disabled="multiple"
          @click="before_send"
          v-hasPermi="['produce:mxSend:send']"
        >
          发送
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['produce:mxSend:delete']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['produce:mxSend:export']"
        >
          导出
        </el-button>
      </el-col>
      <el-col :span="2.2" class="pageLocal">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      highlight-current-row
      v-loading="loading"
      :data="mofMstrList"
      border
      stripe
      :height="tableH"
      ref="somTable"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column
        label="机台"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="mof_jtbh"
      />
      <el-table-column label="机台选择" width="130" align="center">
        <template #default="scope">
          <el-select
            v-model="scope.row.mof_jtbh"
            style="width: 100px"
            filterable
            @change="changeSelect(scope.row)"
            placeholder="请选择机台编号"
            class="inputNameSend"
          >
            <el-option
              v-for="dict in jtmList"
              :key="dict.jtmJtbh"
              :label="dict.jtmJtbh"
              :value="dict.jtmJtbh"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="客户编号"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="itm_custwldm"
      />
      <el-table-column label="模具选择" width="180" align="center">
        <template #default="scope">
          <el-select
            align="center"
            @click.native="getMjmByWldm(scope.row.mof_wldm)"
            v-model="scope.row.mof_mjbh"
            @change="changeSelect1(scope.row)"
            clearable
            placeholder="请选择"
            style="width: 160px"
            class="inputNameSend"
          >
            <el-option
              v-for="dict in mjmList"
              :key="dict.mjmMjbh"
              :label="dict.mjmMjbh"
              :value="dict.mjmMjbh"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column label="模具编号" :show-overflow-tooltip="true" width="180" prop="mof_mjbh" /> -->
      <el-table-column
        label="模具名称"
        :show-overflow-tooltip="true"
        min-width="250"
        align="center"
        prop="mjm_mjmc"
      />
      <el-table-column
        label="计划数量"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mof_zzsl"
      />
      <el-table-column
        label="物料代码"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="mof_wldm"
      />
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        width="400"
        prop="itm_pmgg"
      />
      <el-table-column
        label="已排入机台"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somDdsl"
      />
      <el-table-column
        label="销售单号"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="mof_sodh"
      />
      <el-table-column
        label="制造单号"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="mof_zzdh"
      />
      <el-table-column
        label="组别"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mof_bbdm"
      />
      <el-table-column
        label="材质"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="itm_czdm"
      />
      <el-table-column
        label="颜色"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="itm_ysdm"
      />
      <el-table-column
        label="完工日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="mof_wgrq"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.mof_wgrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="模具尺寸"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mjm_mjgg"
      />
      <el-table-column
        label="可生产模具宽度范围"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mof_jtkd"
      />
      <el-table-column
        label="可生产模具厚度范围"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mof_jthd"
      />
      <el-table-column
        label="可生产原料"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="jtm_czdm"
      />
    </el-table>
  </div>
</template>

<script>
import {
  getSendList,
  sendCheck,
  removeSend,
  send,
} from "@/api/produce/materialScheduling";
import { listJtm } from "@/api/project/jtm";
import { getMjmByWldm } from "@/api/project/mjmMstr";

export default {
  name: "MxSend",
  data() {
    return {
      openSearch: false,
      // 遮罩层
      loading: true,
      tableH: 1,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      mofIds: [],
      mofZzdhs: [],
      currentData: [],
      // 日期范围
      dateRange: [
        new Date(new Date().getTime() - 3600 * 1000 * 24 * 30),
        new Date(new Date().getTime() + 3600 * 1000 * 24 * 3650),
      ],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计划发送作业表格
      mofMstrList: [],
      //机台列表-选择机台
      jtmList: [],
      //根据物料代码得到的模具信息
      mjmList: [],
      //选中的物料代码
      clickWldm: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: document.body.clientHeight > 900 ? 25 : 18,
        mofZzdh: null,
        mofSodh: null,
        mofJtbh: null,
        mofMjbh: null,
        mofWldm: null,
      },
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    //获取所有机台
    listJtm(null).then((res) => {
      this.jtmList = res.rows;
    });
    this.getList();
  },
  methods: {
    /** 查询明细计划发送列表 */
    getList() {
      this.tableH = document.body.clientHeight - 280;
      this.queryParams.params = {};
      if (this.dateRange !== null && this.dateRange != "") {
        this.queryParams.params["beginMofWgrq"] = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParams.params["endMofWgrq"] = this.moment(
          this.dateRange[1]
        ).format("YYYY-MM-DD HH:mm:ss");
      }
      this.loading = true;
      getSendList(this.queryParams).then((response) => {
        this.mofMstrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    clickRow(row) {
      this.$refs.somTable.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.mofZzdhs = selection.map((item) => item.mof_zzdh);
      this.mofIds = selection.map((item) => item.mof_id);
      this.currentData = selection;
      this.multiple = !selection.length;
    },
    /** 查询按钮操作 */
    handleSearch() {
      this.title = "查询明细计划发送作业";
      this.openSearch = true;
    },
    changeSelect(e) {
      for (let i of this.jtmList) {
        if (e.mof_jtbh == i.jtmJtbh) {
          e.mof_bbdm = i.jtmBbdm;
          e.mof_jthd = i.jtmMinhd + "->" + i.jtmMaxhd;
          e.mof_jtkd = i.jtmMinkd + "->" + i.jtmMaxkd;
        }
      }
    },
    changeSelect1(e) {
      for (let i of this.mjmList) {
        if (e.mof_mjbh == i.mjmMjbh) {
          e.mjm_mjmc = i.mjmMjmc;
          e.mjm_mjgg = i.mjmMjgg;
        }
      }
    },
    getMjmByWldm(e) {
      if (e != null && e != "" && e != this.clickWldm) {
        this.clickWldm = e;
        this.mjmList = [];
        getMjmByWldm(this.clickWldm).then((res) => {
          this.mjmList = res.data;
        });
      }
    },
    /** 发送按钮操作-检验操作 */
    before_send() {
      //错误信息
      let uncheck = "";
      let sendMof = [];
      let sendMof1 = [];
      let sendMof2 = [];
      let cgsxList = [
        { cgsx: "M" },
        { cgsx: "ZM" },
        { cgsx: "MM" },
        { cgsx: "S" },
      ];
      // 预检验机台信息
      for (let i of this.currentData) {
        let mof = {
          mofId: i.mof_id,
          mofJtbh: i.mof_jtbh,
          mofMjbh: i.mof_mjbh,
          mofZzdh: i.mof_zzdh,
          mofWldm: i.mof_wldm,
          mofSodh: i.mof_sodh,
        };
        if (i.mof_jtbh == "") {
          alert("机台号不能为空");
          return;
        }
        if (cgsxList.some((s) => i.mol_cgsx === s.cgsx)) {
          if (i.mof_bbdm == "Z") {
            sendMof2.push(mof);
          } else {
            if (i.mof_mjbh == "") {
              alert("模具编号不能为空");
              return;
            }
            sendMof2.push(mof);
          }
        } else {
          sendMof1.push(mof);
        }
      }
      if (sendMof2.length > 0) {
        for (let j of sendMof2) {
          //检验是否合适排入到当前机台
          sendCheck({ moeMjbh: j.mofMjbh, moeJtbh: j.mofJtbh }).then((res) => {
            if (res.msg == null) {
              uncheck += j.mofZzdh + ",";
            }
            if (sendMof2.indexOf(j) == sendMof2.length - 1) {
              sendMof = sendMof2;
              if (sendMof1.length > 0) {
                for (let i of sendMof1) {
                  sendMof.push(i);
                }
              }
              this.send(uncheck, sendMof);
            }
          });
        }
      } else {
        this.send(uncheck, sendMof1);
      }
    },
    /** 发送作业 **/
    send(uncheck, sendMof) {
      if (uncheck != "") {
        uncheck = "制造单号：" + uncheck + "不适合排入此机台，是否继续操作?";
      } else {
        uncheck = "是否将所选取的工单进行发送作业?";
      }
      this.$confirm(uncheck, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const p = sendMof.map((o) => {
            let list1 = [];
            list1.push(o);
            return send(list1);
          });
          Promise.all(p)
            .then(() => {
              this.msgSuccess("发送工单成功");
              this.getList();
            })
            .finally(() => {
              this.getList();
            });
        })
        .catch(() => {
          this.getList();
        });
    },
    /** 删除按钮操作 */
    handleDelete() {
      this.$confirm(
        "确定将【制造单号：" +
          this.mofZzdhs +
          "】的工单删除吗?删除后将返回上一流程，请谨慎操作",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return removeSend(this.mofIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有明细计划发送数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportSom(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .inputNameSend {
  > .el-input--medium .el-input__inner {
    height: 20px;
    font-size: 12px;
  }

  > .el-input--suffix > .el-input__suffix {
    top: 7px;
  }
}
</style>
